//@author A0083782W
#include "HistoryRecord.h"


pos_int HistoryRecord::size() const {
	return _size;
}

void HistoryRecord::push_back (con_str& userInput) {
	if (userInput != NULL_STRING) {
		if (_size == 0) {
			_head = new STRING_LIST_NODE;
			_head->myType = NodeType::HEAD;
			_head->prev = nullptr;
			_head->next = nullptr;
			_head->userInput = userInput;
			_size++;
		}
		else if (_size == 1) {
			_tail = new STRING_LIST_NODE;
			_tail->myType = NodeType::TAIL;
			_head->next = _tail;
			_tail->prev = _head;
			_tail->userInput = userInput;
			_tail->next = nullptr;
			_size++;
		}
		else if (_size <= MAX_RECORD) {
			STRING_LIST_NODE *newNode = new STRING_LIST_NODE;
			newNode->myType = NodeType::TAIL;
			newNode->prev = _tail;
			newNode->userInput = userInput;
			newNode->next = nullptr;
			_tail->next = newNode;
			_tail->myType = NodeType::BODY;
			_tail = newNode;
			_size++;
		}
		else {
			STRING_LIST_NODE *temp = _head;
			_head = _head->next;
			delete temp;
			_head->myType = NodeType::HEAD;
			_head->prev = nullptr;
			_size--;
			this->push_back (userInput);
		}
	}
}

void HistoryRecord::moveToTail() {
	_current = nullptr;
}

string HistoryRecord::getCurrentString() const {
	if (_current != nullptr) {
		return _current->userInput;
	}
	return NULL_STRING;
}

HistoryRecord& HistoryRecord::get() {
	static HistoryRecord newInstance;
	return newInstance;
}

bool HistoryRecord::moveFront() {
	if (_size > 0) {
		if (_current != nullptr) {
			if (_current->myType != NodeType::HEAD) {
				_current = _current->prev;
				return true;
			}
		}
		else {
			if (_size >= 2) {
				_current = _tail;
			}
			else {
				_current = _head;
			}
		}
	}
	return false;
}

bool HistoryRecord::moveBack() {
	if (_size > 1) {
		if (_current != nullptr) {
			if (_current->myType != NodeType::TAIL) {
				_current = _current->next;
				return true;
			}
		}
	}
	return false;
}

void HistoryRecord::reset() {
	while (_size > 0) {
		if (_size == 1) {
			delete _head;
		}
		else if (_size == 2){
			delete _tail;
		}
		else {
			STRING_LIST_NODE* temp;
			temp = _tail;
			_tail = _tail->prev;
			delete temp;
		}
		_size--;
	}
	_size = 0;
	_current = nullptr;
	_head = nullptr;
	_tail = nullptr;
}

HistoryRecord::~HistoryRecord() {
	reset();
}

HistoryRecord::HistoryRecord() {
	_size = 0;
	_head = nullptr;
	_tail = nullptr;
	_current = nullptr;
}
